package com.sskj.level.ui.fragment;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.CoinType;
import com.sskj.level.bean.Entrust;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.CurrentHolderFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.MainTabChange;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.bigkoo.pickerview.view.WheelTime.dateFormat;

@Route(path = RConfig.LEVEL_FRAGMENT_CURRENT_HOLDER)//当前委托
public class CurrentHolderFragment extends BaseFragment<CurrentHolderFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.includeEmpty)
    View includeEmpty;

    private SlimAdapter<Entrust> slimAdapter;
    @Autowired
    String code;
    private int curPos;
    @Inject
    UserViewModel userViewModel;

    private Disposable subscribe;
    private MaterialDialog setTip;
    private UserData userData;
    private MaterialDialog cancelTip;


    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_current_holder;
    }

    @Override
    public CurrentHolderFragmentPresenter getPresenter() {
        return new CurrentHolderFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);

        ARouter.getInstance().inject(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapter = SlimAdapter.create().register(R.layout.item_recycler_entrust, new SlimInjector<Entrust>() {
            @Override
            public void onInject(Entrust item, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.item_entrust_name, item.getPname())
                        .text(R.id.item_entrust_type, item.getType() == 1 ? App.INSTANCE.getString(R.string.levelCurrentHolderFragment12) : App.INSTANCE.getString(R.string.levelCurrentHolderFragment13))
                        .textColor(R.id.item_entrust_type, item.getType() == 1 ? getResources().getColor(R.color.levelGreenText) : getResources().getColor(R.color.levelRedText))
                        .text(R.id.item_entrust_time, dateFormat.format(Long.parseLong(item.getAdd_time()) * 1000))
                        .text(R.id.item_entrust_price, item.getWtprice1())
                        .text(R.id.item_entrust_real_num, item.getCjnum());
                if (item.getOtype() == 2 && item.getType() == 1) {  //市价买入
                    injector.text(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strEntrustActivity203))
                            .text(R.id.item_entrust_num, item.getTotalprice());
                } else { //其他
                    injector.text(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strEntrustActivity204))
                            .text(R.id.item_entrust_num, item.getWtnum());
                }

                TextView cancel = (TextView) injector.findViewById(R.id.item_entrust_cancel);

                cancel.setText(App.INSTANCE.getString(R.string.strEntrustActivity205));
                cancel.setOnClickListener(v -> mPresenter.cancelOrder(item.getOrders_id()));
                cancel.setTextColor(getResources().getColor(R.color.blue_5d));


            }
        }).attachTo(recyclerView).updateData(new ArrayList());

        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                //   startTimer();
            } else {
                userData = null;
            }
            refresh();
        });
    }

    public void pingCangSuccess() {
        userViewModel.update();
        refresh();
    }

    public void cancelOrderSuccess() {
        userViewModel.update();
        refresh();
    }

    /**
     * 刷新
     */
    @Subscribe(code = RxBusCode.LEVEL_FRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        if (mPresenter != null && userData != null) {
            mPresenter.getTradeList(code, 0 + "");
        } else {
            DisposUtil.close(subscribe);
            showEmpty();
        }
    }

    /**
     * 显示无数据布局
     */
    public void showEmpty() {
        AndroidSchedulers.mainThread().scheduleDirect(() -> {

            if (includeEmpty != null) {
                includeEmpty.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
            if (slimAdapter != null) {
                slimAdapter.updateData(new ArrayList<>());
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(CoinBean stockCoinBean) {
        if (setTip != null && setTip.isShowing()) {
            if (stockCoinBean.getCode().equals(slimAdapter.getDataItem(curPos).getPname())) {
                TipLevelUtil.changeTradeSet(setTip, stockCoinBean.getPrice());
            }
        }

    }

    private void startTimer() {
        if (userData == null)
            return;
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getTradeList(code, 0 + ""));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(MainTabChange mainTabChange) {
        if (mainTabChange.getPos() == 2) {
            if (mPresenter != null && userData != null) {
                startTimer();
            }
        } else {
            DisposUtil.close(subscribe);
        }
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(subscribe);
        super.onDestroy();
    }

    /**
     * 刷新币种
     *
     * @param coinType
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CoinType coinType) {
        code = coinType.getCode();
        if (userData == null)
            return;
        mPresenter.getTradeList(code, "0");
    }


    public void updateUI(List<Entrust> data) {
        if (data == null || data.size() == 0) {
            if (recyclerView == null)
                return;
            recyclerView.setVisibility(View.GONE);
            includeEmpty.setVisibility(View.VISIBLE);
        } else {
            if (recyclerView == null)
                return;
            recyclerView.setVisibility(View.VISIBLE);
            includeEmpty.setVisibility(View.GONE);
            slimAdapter.updateData(data);
        }
    }
}
